package cn.flexui.flexuiserver.service.impl;

import cn.flexui.flexuiserver.domain.entity.BaseEntity;
import cn.flexui.flexuiserver.domain.entity.ChatCodeRecord;
import cn.flexui.flexuiserver.domain.entity.ChatRecord;
import cn.flexui.flexuiserver.mapper.ChatRecordMapper;
import cn.flexui.flexuiserver.service.ChatCodeRecordService;
import cn.flexui.flexuiserver.service.ChatRecordService;
import cn.flexui.flexuiserver.service.FileInfoDetailService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.get.RemoteFileInfo;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 对话记录 服务实现类
 * </p>
 *
 * @author apeto
 * @since 2024-09-17 07:08:21
 */
@Slf4j
@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper, ChatRecord> implements ChatRecordService {

    @Autowired
    private FileInfoDetailService fileInfoDetailService;
    @Autowired
    private ChatCodeRecordService chatCodeRecordService;

    @Override
    public List<ChatRecord> selectRequestId(String requestId) {

        return list(new LambdaQueryWrapper<ChatRecord>().eq(ChatRecord::getRequestId, requestId).orderByAsc(BaseEntity::getId));

    }

    @Override
    public void userChatRecord(ChatClient.PromptUserSpec consumer, String message, String fileIds, String requestId, long userId) {
        consumer = consumer.text(message);
        ChatRecord chatRecord = new ChatRecord();
        if (StrUtil.isNotBlank(fileIds)) {
            String[] split = fileIds.split(",");
            RemoteFileInfo remoteFileInfo = fileInfoDetailService.getRemoteFileInfo(Long.valueOf(split[0]));
            MimeType mimeType = MimeTypeUtils.parseMimeType(remoteFileInfo.getContentType());
            try {
                consumer.media(mimeType, new URL(remoteFileInfo.getUrl()));
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
            chatRecord.setMedia(mimeType.getType());
        }
        chatRecord.setUserId(userId);
        chatRecord.setMedia(MimeTypeUtils.TEXT_PLAIN_VALUE);
        chatRecord.setMessageType(MessageType.USER.getValue());
        chatRecord.setRequestId(requestId);
        chatRecord.setContent(message);
        save(chatRecord);
    }

    @Override
    public void assistantChatRecord(String requestId, long userId, StringBuilder builder) {
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setUserId(userId);
        chatRecord.setRequestId(requestId);
        chatRecord.setMessageType(MessageType.ASSISTANT.getValue());
        chatRecord.setMedia(MimeTypeUtils.TEXT_PLAIN_VALUE);
        chatRecord.setContent(builder.toString());
        save(chatRecord);
        doSaveCode(chatRecord);

    }

    public void doSaveCode(ChatRecord chatRecord) {

        try {
            String content = chatRecord.getContent();
            String requestId = chatRecord.getRequestId();
            Long userId = chatRecord.getUserId();
            Long chatRecordId = chatRecord.getId();

            List<String> strings = parseArtifact(content);
            ChatCodeRecord chatCodeRecord = new ChatCodeRecord();
            chatCodeRecord.setChatRecordId(chatRecordId);
            chatCodeRecord.setUserId(userId);
            chatCodeRecord.setRequestId(requestId);
            chatCodeRecord.setCode(strings.get(0));
            chatCodeRecord.setCodeType(strings.get(2));
            chatCodeRecord.setTitle(strings.get(3));
            chatCodeRecord.insert();

        } catch (Exception e) {
            log.error("保存代码异常", e);
        }

    }

    public static List<String> parseArtifact(String str) {
        // 定义更灵活的正则表达式模式
        Pattern pattern = Pattern.compile("<artifact\\s+(.*?)>(.*?)</artifact>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(str);
        List<String> attrs = new ArrayList<>();
        if (matcher.find()) {

            String content = matcher.group(2);
            attrs.add(content);
            // 解析属性
            String attributes = matcher.group(1);
            Pattern attrPattern = Pattern.compile("(\\w+)\\s*=\\s*\"(.*?)\"");
            Matcher attrMatcher = attrPattern.matcher(attributes);
            while (attrMatcher.find()) {
//                String attrName = attrMatcher.group(1);
                String attrValue = attrMatcher.group(2);
                attrs.add(attrValue);
            }
        }
        return attrs;
    }

    @Data
    public static class ArtifactInfo {

        private String identifier;
        private String type;
        private String title;
        private String content;
    }

    private static String convertToSlug(String str) {
        // 替换非字母数字字符为空格
        return str.replaceAll("[^a-zA-Z0-9\\s+]", " ")
                // 将多个空格替换为一个空格
                .replaceAll("\\s+", " ")
                // 转换为小写
                .toLowerCase()
                // 将空格替换为下划线
                .replaceAll(" ", "_");
    }
}
